package com.tengju.activity.domain.shared;



import org.apache.commons.lang3.StringUtils;

import java.text.NumberFormat;

public class CastUtil {

    public static int castInt(Object obj) {
        return castInt(obj, 0);
    }

    private static int castInt(Object obj, int defaultValue) {
        int intValue = defaultValue;
        if (obj != null) {
            String stringValue = castString(obj);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    intValue = Integer.parseInt(stringValue);
                } catch (NumberFormatException e) {
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }

    public static double castDouble(Object obj) {
        return castDouble(obj, 0d);
    }

    private static double castDouble(Object obj, double defaultValue) {
        double doubleValue = defaultValue;
        if (obj != null) {
            String stringValue = castString(obj);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    doubleValue = Double.parseDouble(stringValue);
                } catch (NumberFormatException e) {
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    public static long castLong(Object obj) {
        return castLong(obj, 0l);
    }

    private static long castLong(Object obj, long defaultValue) {
        long longValue = defaultValue;
        if (obj != null) {
            String stringValue = castString(obj);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    longValue = Long.parseLong(stringValue);
                } catch (NumberFormatException e) {
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    public static String castString(Object obj) {
        return castString(obj, "");
    }

    private static String castString(Object obj, String defaultValue) {
        return obj == null ? defaultValue : String.valueOf(obj);
    }

    public static boolean castBoolean(Object obj) {
        return castBoolean(obj, false);
    }

    private static boolean castBoolean(Object obj, boolean defaultValue) {
        boolean bolValue = defaultValue;
        if (obj != null) {
            bolValue = Boolean.parseBoolean(castString(obj));
        }
        return bolValue;
    }

    public static String castPercentage(Object obj,int scale) {
        double value = castDouble(obj);
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMaximumFractionDigits(scale);
        return format.format(value);
    }

}
